package com.free.bsf.elasticsearch.base;

import com.free.bsf.core.util.ContextUtils;
import com.free.bsf.core.util.ConvertUtils;
import com.free.bsf.elasticsearch.impl.ElasticSearchSqlProvider;
import lombok.val;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.lucene.queryparser.classic.QueryParser;

import java.util.*;

/**
 * @Classname Param
 * @Description es sql 参数
 * @Date 2021/4/15 18:08
 * @Created by chejiangyi
 */
public class Param {
    private Map<String,Object> ps1;
    private List<Object> ps2;
    public static Param create(){
        return new Param();
    }
    public static Param create(Object... objects){
        return new Param().add(objects);
    }
    public Param add(String key,Object value){
        if(ps1==null){
            ps1= new HashMap<>();
        }
        ps1.put(key,value);
        return this;
    }
    public Param add(Object... values){
        if(ps2==null){
            ps2= new ArrayList<>();
        }
        for(val o:values){
            ps2.add(o);
        }
        return this;
    }
    public String build(String sql){
        if(ps1!=null){
            for(val kv:this.ps1.entrySet()){
                kv.setValue(filterParam(kv.getValue()));
            }
            StrSubstitutor ss = new StrSubstitutor(this.ps1);
            return ss.replace(sql);
        }
        if(ps2!=null){
            for(int i=0;i<this.ps2.size();i++){
                ps2.set(i,filterParam(ps2.get(i)));
            }
            sql = sql.replace("{}","%s");
            sql = String.format(sql,this.ps2.toArray());
            return sql;
        }
        return sql;
    }

    private Object filterParam(Object obj){
        if(obj==null)
            return "null";
        if(obj instanceof Date){
            return ContextUtils.getBean(ElasticSearchSqlProvider.class,true).formatDate((Date)obj);
        }
        return QueryParser.escape(ConvertUtils.convert(obj,String.class));
    }
}
